<?php

/**
 * 验证类
 */
class Code
{
	public $config = [
		'width'=>200,   
		'heigth'=>80,
		'length'=>4,
		'fontsize'=>40,
		'disturb'=>60,
		'bg_color'=>[255,255,255],
		'str'=>"qwertyuiopasdfghjklzxcvbnm1234567890"
	];
	public $src; //画布
	public function __construct($configs=[])
	{
		$this->config = array_merge($this->config,$configs);

		// todo:: 调用一个方法实现验证宽度与字体大小的合理性
	}
	public function __get($key)
	{
		return $this->config[$key];
	}
	public function entry()
	{
		// var_dump($this->length);
		// todo:: 生成画布
		$this->src = imageCreateTrueColor($this->width,$this->heigth);
		// todo:: 填充颜色
		$color = imageColorAllocate($this->src,$this->bg_color[0],$this->bg_color[1],$this->bg_color[2]); 

		imageFill($this->src,0,0,$color);
		// todo:: 画干扰
		
		$this->add_disturb();

		// todo:: 画字体
		$this->add_fonts();
		// todo:: 输出 
		$this->output();
	}

	public function add_disturb()
	{
		if($this->disturb){

			for ($i=0; $i <$this->disturb ; $i++) { 

				$color = imageColorAllocate($this->src,mt_rand(150,255),mt_rand(150,255),mt_rand(150,255)); 

				$s = $this->str[mt_rand(0,strlen($this->str)-1)];

				imagettftext($this->src, 10, mt_rand(-30,30),mt_rand(0,$this->width),mt_rand(0,$this->heigth), $color,COMMON_PATH.'/titania.ttf', $s);
			}

		}
	}

	public function add_fonts()
	{
		for ($i=0; $i <$this->length ; $i++) { 

			$color = imageColorAllocate($this->src,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100)); 

			$s = $this->str[mt_rand(0,strlen($this->str)-1)];

			$w = $i*($this->width/$this->length)+(($this->width/$this->length)-$this->fontsize*0.7)/2;

			$h = ($this->heigth+$this->fontsize)/2;

			imagettftext($this->src, $this->fontsize, mt_rand(-30,30), $w, $h, $color,COMMON_PATH.'/titania.ttf', $s);
		}
	}

	public function output()
	{
		// todo:: 声明头部
		header("Content-type: image/png");
		// todo:: 输出
		imagepng($this->src);
		
	}
}
